from app.spider.yushu_book import YuShuBook
from .base import db, Base
from sqlalchemy import func


class Gift(Base):
    ''' 用户和赠送书籍关系表 '''
    id = db.Column(db.Integer, primary_key=True)
    uid = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
    user = db.relationship('User') # 方便查询的关系属性
    isbn = db.Column(db.String(13))
    launched = db.Column(db.Boolean, default=False) # 是否赠送成功

    @property
    def book(self):
        # 拿到当前书籍的信息.
        yushu_book = YuShuBook()
        yushu_book.search_by_isbn(self.isbn)
        return yushu_book.first

    @classmethod
    def get_wish_counts(cls, isbn_list):
        from app.models.wish import Wish
        # 查询我赠送的书籍,有多少人想要.
        wish_list = db.session.query(func.count(Wish.id), Wish.isbn).\
            filter(Wish.launched == False, Wish.status == 1, Wish.isbn.in_(isbn_list)).\
            group_by(Wish.isbn).all()
        wish_dict = [{'count':i[0], 'isbn':i[1]} for i in wish_list]
        return wish_dict

    @classmethod
    def get_user_gifts(cls, uid):
        return Gift.query.filter_by(uid=uid, launched=False).order_by(db.desc(Gift.create_time)).all()

    @classmethod
    def recent(cls):
        recent_gift = Gift.query.filter_by(launched=False).\
            order_by(db.desc(Gift.create_time)).\
            limit(30).distinct().all()
        return recent_gift

    def is_youself_gift(self, uid):
        return True if self.uid == uid else False